﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Data;
using org.in2bits.MyXls;

namespace NJL.WebManage.Orders
{
    public partial class OrderCount : BasePage
    {
        PagedDataSource pds;
        NJL.BLL.NJL_BOOK_ORDER bll = new BLL.NJL_BOOK_ORDER();
        NJL.BLL.NJL_CS_AREA bllArea = new BLL.NJL_CS_AREA();
        NJL.BLL.NJL_SYS_CONTACT bllContact = new BLL.NJL_SYS_CONTACT();
        private readonly NJL.BLL.NJL_ATTRACTION bllAttr = new BLL.NJL_ATTRACTION();
        private readonly NJL.BLL.NJL_COMPANY bllCompany = new BLL.NJL_COMPANY();
        protected NJL.Model.NJL_ATTRACTION modelAttr;
        protected NJL.Model.NJL_COMPANY modelCompany;
        NJL.BLL.NJL_SYS_BASE bllSysBase = new BLL.NJL_SYS_BASE();
        NJL.Model.NJL_SYS_BASE modelSysBase;
        NJL.Model.NJL_BOOK_ORDER model;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (WEBSITE_CODE != "1")
                {
                    ds = bllCompany.GetAllList("IS_OPEN_BOOK=1 and AUDIT_STATE=1 and NJL_SYS_BASE_ID='" + WEBSITE_CODE + "'");
                }
                else
                {
                    ds = bllCompany.GetAllList("IS_OPEN_BOOK=1 and AUDIT_STATE=1");
                }
                dropCompanyName.DataSource = ds;
                dropCompanyName.DataTextField = "COMPANY_NAME";
                dropCompanyName.DataValueField = "ID";
                dropCompanyName.DataBind();
                dropCompanyName.Items.Insert(0, new ListItem("请选择商户", "0"));
                txtStartTime.Text = DateTime.Now.ToShortDateString();
                txtEndTime.Text = DateTime.Now.ToShortDateString();
                ViewState["pager"] = "0";
                if (WEBSITE_CODE == "1")
                {
                    ds = bllArea.GetList("AREA_CODE like '%0000'");
                    ddlarea.DataSource = ds;
                    ddlarea.DataTextField = "AREA_NAME";
                    ddlarea.DataValueField = "AREA_CODE";
                    ddlarea.DataBind();
                }
                else
                {
                    dispArea.Visible = false;
                }
                bind();
            }
        }
        public void bind()
        {
            txtPage.Text = (Convert.ToInt32(ViewState["pager"]) + 1).ToString();
            ds = bll.GetOrderCountInCompany(sql());
            pds = new PagedDataSource();
            pds.DataSource = ds.Tables[0].DefaultView;
            pds.AllowPaging = true;
            pds.PageSize = 15;
            pds.CurrentPageIndex = Convert.ToInt32(ViewState["pager"]);
            ViewState["endpage"] = pds.PageCount;
            lbtnFirst.Enabled = true;
            lbtnPrev.Enabled = true;
            lbtnNext.Enabled = true;
            lbtnEnd.Enabled = true;
            if (ViewState["pager"].ToString() == "0")
            {
                lbtnFirst.Enabled = false;
                lbtnPrev.Enabled = false;
            }
            if (Convert.ToInt32(ViewState["pager"]) == pds.PageCount - 1)
            {
                lbtnNext.Enabled = false;
                lbtnEnd.Enabled = false;
            }
            lit.Text = ds.Tables[0].Rows.Count.ToString();
            litAllPage.Text = pds.PageCount.ToString();
            litCurrentPage.Text = (pds.CurrentPageIndex + 1).ToString();
            rptUserList.DataSource = ds;
            rptUserList.DataBind();
        }
        public string sql()
        {
            string sql = "b.TYPE_CODE='2' and c.ID='" + dropCompanyName.SelectedValue + "' and b.BOOK_NAME like '%" + txtTicketType.Text.Trim() + "%' and a.ORDER_NO like '%" + txtKeywords.Text.Trim() + "%' and (a.VISIT_DATE BETWEEN '" + txtStartTime.Text.Trim() + "' and '" + txtEndTime.Text.Trim() + "')";
            if (ddlIsRegister.SelectedValue != "-1")
            {
                sql += " and a.IS_REGISTER_USER=" + ddlIsRegister.SelectedValue;
            }
            if (ddlIsGroup.SelectedValue == "1")
            {
                sql += " and a.TICKET_COUNT>=b.GROUP_MIN_COUNT";
            }
            else if (ddlIsGroup.SelectedValue == "0")
            {
                sql += " and a.TICKET_COUNT<b.GROUP_MIN_COUNT";
            }
            if (WEBSITE_CODE == "1")
            {
                if (ddlarea.SelectedValue != "000000")
                {
                    sql += " and a.NJL_SYS_BASE_ID='" + ddlarea.SelectedValue + "'";
                }
            }
            else
            {
                sql += " and a.NJL_SYS_BASE_ID='" + WEBSITE_CODE + "'";
            }
            return sql;
        }
        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            ViewState["pager"] = "0";
            bind();
        }

        protected void lbtnPrev_Click(object sender, EventArgs e)
        {
            ViewState["pager"] = Convert.ToInt32(ViewState["pager"]) - 1;
            bind();
        }

        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            ViewState["pager"] = Convert.ToInt32(ViewState["pager"]) + 1;
            bind();
        }

        protected void lbtnEnd_Click(object sender, EventArgs e)
        {
            ViewState["pager"] = Convert.ToInt32(ViewState["endpage"]) - 1;
            bind();
        }
        private static Regex RegNumber = new Regex("^[0-9]+$");
        protected void btnRir_Click(object sender, EventArgs e)
        {
            Match mc = RegNumber.Match(txtPage.Text);
            if (mc.Success && txtPage.Text != "0")
            {
                ViewState["pager"] = Convert.ToInt32(txtPage.Text) - 1;
                bind();
            }
        }
        protected void btnDel_Click1(object sender, EventArgs e)
        {
            string[] cbxid = HSelectId.Value.Split(',');
            foreach (string id in cbxid)
            {
                if (bll.Delete(id))
                {
                    bind();
                }
                else
                {
                    Royalsoft.Common.MessageBox.Show(this, "删除失败");
                }
            }
        }
        protected void rptUserList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            //if (e.CommandName == "linkbtn")
            //{
            //    string id = e.CommandArgument.ToString();
            //    model = bll.GetModel(id);
            //    if (model.ORDER_STATE == 0)
            //    {
            //        model.ORDER_STATE = 1;
            //    }
            //    if (bll.Update(model))
            //    {
            //        bind();
            //    }
            //    else
            //    {
            //        Royalsoft.Common.MessageBox.Show(this, "审核失败");
            //    }
            //}
        }
        protected void rptUserList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Literal lit = e.Item.FindControl("litNum") as Literal;
                lit.Text = (e.Item.ItemIndex + 1).ToString();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            bind();
        }
        protected void btnConvertExcel_Click(object sender, EventArgs e)
        {
            //string id = string.Empty;
            //string[] hidSelectId = HSelectId.Value.Split(',');
            //foreach (string hidSId in hidSelectId)
            //{
            //    id += "'" + hidSId + "',";
            //}
            //ds = bll.GetOrderCountInCompany(sql() + " and a.ID in(" + id.Substring(0, id.Length - 1) + ")");
            //ExportExcel(ds.Tables[0], "FileName.xls");
            //foreach (string sid in hidSelectId)
            //{
            //    model = bll.GetModel(sid);
            //    model.ORDER_OUTPUT_PRINT_COUNT += 1;
            //    if (bll.Update(model))
            //    {

            //    }
            //}
            modelCompany = bllCompany.GetModel(dropCompanyName.SelectedValue);
            modelSysBase = bllSysBase.GetModel(modelCompany.NJL_SYS_BASE_ID);

            //取传真
            ds = bllContact.GetList("NJL_SYS_BASE_ID='" + modelSysBase.ID + "' and TYPE_CODE='PWKF'");
            if (ds.Tables[0].Rows.Count > 0)
            {
                ltlFaxXls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_FAX"].ToString();
                ltlFax1Xls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_FAX"].ToString();
                ltlEmailXls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_EMAIL"].ToString();
                ltlContactXls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT"].ToString();
                ltlTelXls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_TEL"].ToString();
                litWebSiteContactXls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT"].ToString(); //网站联系人
                litWebSiteTelXls.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_TEL"].ToString(); //联系方式
            }
            ltlWebSiteNameXls.Text = modelSysBase.WEBSITE_NAME;//网站名称
            ltlUrlXls.Text = modelSysBase.WEBSITE_DOMAIN;      //网站域名
    

            modelCompany = bllCompany.GetModel(dropCompanyName.SelectedValue);
            ltlCompanyContactXls.Text = modelCompany.CONTACT;
            ltlCompanyNameXls.Text = modelCompany.COMPANY_NAME;
            ltlCompanyFaxXls.Text = modelCompany.FAX;
            ltlCompanyTelXls.Text = modelCompany.MOBILE;
   
            string id = string.Empty;
            string[] hidSelectId = HSelectId.Value.Split(',');
            foreach (string hidSId in hidSelectId)
            {
                id += "'" + hidSId + "',";
            }
            ds = bll.GetOrderCountInCompany(sql() + " and a.ID in(" + id.Substring(0, id.Length - 1) + ")");
            int allTicket = 0;
            decimal allPrice = 0;
            foreach (DataRow ticketNum in ds.Tables[0].Rows)
            {
                allTicket += Convert.ToInt32(ticketNum["TICKET_COUNT"]);
                allPrice += Convert.ToDecimal(ticketNum["TICKET_COUNT"]) * Convert.ToDecimal(ticketNum["BOOK_PRICE"]);
            }
            ltlOrderSumXls.Text = allTicket.ToString(); //订票总数量
            ltlOrderSum1Xls.Text = allTicket.ToString();
            ltlSumPriceXls.Text = string.Format("{0:0.00}", allPrice);  //订票总价格
            ltlSumPrice1Xls.Text = string.Format("{0:0.00}", allPrice);
            foreach (string sid in hidSelectId)
            {
                model = bll.GetModel(sid);
                model.ORDER_OUTPUT_PRINT_COUNT += 1;
                if (bll.Update(model))
                {

                }
            }
            rptOrderReportXls.DataSource = ds;
            rptOrderReportXls.DataBind();
            if (!Page.ClientScript.IsClientScriptBlockRegistered("excel"))
                Page.ClientScript.RegisterStartupScript(GetType(), "excel", "<script >OutToFileMoreSheet();</script>");
            bind();


        }
        public void ToExcel(System.Web.UI.Control ctl, string FileName)
        {
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName + ".xls");
            ctl.Page.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            ctl.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }//导入excel 
        public void ExportExcel(DataTable dtSource, string strFileName)
        {
            modelCompany = bllCompany.GetModel(dropCompanyName.SelectedValue);
            modelSysBase = bllSysBase.GetModel(WEBSITE_CODE);
            XlsDocument xls = new XlsDocument();
            Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");

            //填充表头   
            //foreach (DataColumn col in dtSource.Columns)
            //{
            //    sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName);
            //}
            sheet.Cells.Add(1, 1, modelSysBase.WEBSITE_NAME + "(" + modelSysBase.WEBSITE_DOMAIN + ")-网上订票核查表");

            sheet.Cells.Add(2, 1, "商户名称: " + dropCompanyName.SelectedItem.Text);
            sheet.Cells.Add(3, 1, "网站联系人: " + modelSysBase.WEBSITE_CONTACT + "  " + modelSysBase.WEBSITE_CONTACT_TEL + "               商户联系人：" + modelCompany.CONTACT + " " + modelCompany.MOBILE);
            sheet.Cells.Add(4, 1, "订单编号");
            sheet.Cells.Add(4, 2, "姓名");
            sheet.Cells.Add(4, 3, "联系电话 ");
            sheet.Cells.Add(4, 4, "订票类型");
            sheet.Cells.Add(4, 5, "团/散 ");
            sheet.Cells.Add(4, 6, "预订");
            sheet.Cells.Add(4, 7, "优惠价");
            sheet.Cells.Add(4, 8, "游玩日期 ");
            sheet.Cells.Add(4, 9, "实到 ");
            //填充内容  
            int i;
            for (i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count - 2; j++)
                {
                    if (j == 4 && Convert.ToInt32(dtSource.Rows[i]["TICKET_COUNT"]) >= Convert.ToInt32(dtSource.Rows[i]["GROUP_MIN_COUNT"]))
                    {
                        sheet.Cells.Add(i + 5, j + 1, "团");                        
                    }
                    else if (j == 4 && Convert.ToInt32(dtSource.Rows[i]["TICKET_COUNT"]) < Convert.ToInt32(dtSource.Rows[i]["GROUP_MIN_COUNT"]))
                    {
                        sheet.Cells.Add(i + 5, j + 1, "散");
                    }
                    else
                    {
                        sheet.Cells.Add(i + 5, j + 1, dtSource.Rows[i][j].ToString());
                    }
                }
            }
            sheet.Cells.Add(i + 6, 1, "请准确填写实到数量,可以用两种方式回传给我们：");
            sheet.Cells.Add(i + 7, 1, "1.发送传真，传真号码:027:86865959 2.电子邮箱:piaowu@hbnjl.cn。");
            sheet.Cells.Add(i + 8, 1, "如有疑问，请联系票务专员:" + modelSysBase.WEBSITE_CONTACT + " " + modelSysBase.WEBSITE_CONTACT_TEL);

            //保存   
            // xls.FileName = strFileName;
            // xls.Save();
            xls.Send();


        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {

            modelCompany = bllCompany.GetModel(dropCompanyName.SelectedValue);
            modelSysBase = bllSysBase.GetModel(modelCompany.NJL_SYS_BASE_ID);

            //取传真
            ds = bllContact.GetList("NJL_SYS_BASE_ID='" + modelSysBase.ID + "' and TYPE_CODE='PWKF'");
            if (ds.Tables[0].Rows.Count > 0)
            {
                ltlFax.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_FAX"].ToString();
                ltlFax1.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_FAX"].ToString();
                ltlEmail.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_EMAIL"].ToString();
                ltlContact.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT"].ToString();
                ltlTel.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_TEL"].ToString();
                litWebSiteContact.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT"].ToString(); //网站联系人
                litWebSiteTel.Text = ds.Tables[0].Rows[0]["WEBSITE_CONTACT_TEL"].ToString(); //联系方式
            }
            ltlWebSiteName.Text = modelSysBase.WEBSITE_NAME;                                 //网站名称
            ltlUrl.Text = modelSysBase.WEBSITE_DOMAIN;                                       //网站域名          
            modelCompany = bllCompany.GetModel(dropCompanyName.SelectedValue);
            ltlCompanyContact.Text = modelCompany.CONTACT;
            ltlCompanyName.Text = modelCompany.COMPANY_NAME;
            ltlCompanyFax.Text = modelCompany.FAX;
            ltlCompanyTel.Text = modelCompany.MOBILE;
            if (modelCompany.NJL_SYS_BASE_ID == "420000")
            {
                imgLogo.Src = "/Images/bus_logo02.jpg";
            }
            else if (modelCompany.NJL_SYS_BASE_ID == "610000")
            {
                imgLogo.Src = "/Images/bus_logo03.jpg";
            }
            else if (modelCompany.NJL_SYS_BASE_ID == "110000")
            {
                imgLogo.Src = "/Images/bus_logo01.jpg";
            }
            else if (modelCompany.NJL_SYS_BASE_ID == "500000")
            {
                imgLogo.Src = "/Images/bus_logo04.jpg";
            }
            else if (modelCompany.NJL_SYS_BASE_ID == "430000")
            {
                imgLogo.Src = "/Images/bus_logo05.jpg";
            }
            string id = string.Empty;
            string[] hidSelectId = HSelectId.Value.Split(',');
            foreach (string hidSId in hidSelectId)
            {
                id += "'" + hidSId + "',";
            }
            ds = bll.GetOrderCountInCompany(sql() + " and a.ID in(" + id.Substring(0, id.Length - 1) + ")");
            int allTicket = 0;
            decimal allPrice = 0;
            foreach (DataRow ticketNum in ds.Tables[0].Rows)
            {
                allTicket += Convert.ToInt32(ticketNum["TICKET_COUNT"]);
                allPrice += Convert.ToDecimal(ticketNum["TICKET_COUNT"]) * Convert.ToDecimal(ticketNum["BOOK_PRICE"]);
            }
            ltlOrderSum.Text = allTicket.ToString(); //订票总数量
            ltlOrderSum1.Text = allTicket.ToString();
            ltlSumPrice.Text = string.Format("{0:0.00}", allPrice);  //订票总价格
            ltlSumPrice1.Text = string.Format("{0:0.00}", allPrice);
            foreach (string sid in hidSelectId)
            {
                model = bll.GetModel(sid);
                model.ORDER_OUTPUT_PRINT_COUNT += 1;
                if (bll.Update(model))
                {

                }
            }
            rptOrderReport.DataSource = ds;
            rptOrderReport.DataBind();
            if (!Page.ClientScript.IsClientScriptBlockRegistered("print"))
                Page.ClientScript.RegisterStartupScript(GetType(), "print", "<script >PreviewSameStyle();</script>");
            bind();
        }

        protected void rptOrderReport_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Literal lit = e.Item.FindControl("litNum") as Literal;
                lit.Text = (e.Item.ItemIndex + 1).ToString();
            }
        }

    }
}